#include "Event.h"
#include "CoreSystem.h"

namespace Audio
{
	bool Event::Update(float delta, CoreSystem* core)
	///////////////////////////////////////////////////////////////////////////////
	// Description: Returns true if event is done, false otherwise
	//
	// Recent Changes:
	// -brasmuss 3/30/2007 : Created
	///////////////////////////////////////////////////////////////////////////////
	{
		// Update time
		m_time += delta;

		// Activate queued sub-events
		subeventqueue_t::iterator q_iter = m_queuedSubEvents.begin();
		while(q_iter != m_queuedSubEvents.end()) {
			// Time to activate?
			if(m_time > q_iter->first) {
				// Add to active list
				SubEvent* subEvent = q_iter->second;
				q_iter = m_queuedSubEvents.erase(q_iter);
				ChannelHandle cHandle = core->PlayFile(subEvent->GetFileHandle(),true);
				subEvent->SetChannelHandle(cHandle);
				m_activeSubEvents.push_back(subEvent);
			}
			else
				++q_iter;
		}

		// Update active sub-events
		subeventlist_t::iterator a_iter = m_activeSubEvents.begin();
		while(a_iter != m_activeSubEvents.end()) {
			SubEvent* subEvent = *a_iter;
			if(!subEvent->Update(delta,core)) {
				delete subEvent;
				a_iter = m_activeSubEvents.erase(a_iter);
				continue;
			}
			// dead?
			++a_iter;
		}
		return m_activeSubEvents.empty() && m_queuedSubEvents.empty();
	}

	void Event::AddSubEvent(SubEvent* subEvent, float time)
	///////////////////////////////////////////////////////////////////////////////
	// Description: Used during event creation.  Pushes an inactive sub-event
	//				onto the list
	//
	// Recent Changes:
	// -brasmuss 4/3/2007 : Created
	///////////////////////////////////////////////////////////////////////////////
	{
		m_queuedSubEvents.push_back(subeventpair_t(time,subEvent));
	}

	bool SubEvent::Update(float, CoreSystem* core)
	///////////////////////////////////////////////////////////////////////////////
	// Description: Loops through all the effects and calls the functions
	//
	// Recent Changes:
	// -brasmuss 4/3/2007 : Created
	///////////////////////////////////////////////////////////////////////////////
	{
		// Does channel still exist?
		sndcore::Channel* channel = core->GetChannel(m_channel);
		if(!channel)
			return false;

		// Apply all effects
		effectlist_t::iterator iter = m_effects.begin();
		while(iter != m_effects.end()) {
			Effect* effect = *iter;
			float input = core->GetVariableValue(effect->m_variable,effect->m_xmlFile);
			float output = core->GetGraphOutput(effect->m_graph,input,effect->m_xmlFile);
			effect->m_func(output,channel);
			++iter;
		}
		return true;
	}
}